package example.dao.ibatis;

import java.io.InputStream;
import java.io.InputStreamReader;

import com.ibatis.dao.client.DaoException;
import com.ibatis.dao.client.DaoManager;
import com.ibatis.dao.client.DaoManagerBuilder;

import example.dao.IAccountDao;
import example.dao.IFactoryDAO;


public class FactoryIbatisDAO implements IFactoryDAO {

	private final static String CONTEXT_NAME = "account";
	private DaoManager daoManager;
	
	private IAccountDao accountDao;
	
	private FactoryIbatisDAO(){
		init();
	}
	
	private void init() {
		String daoConfigFile = "dao.xml";		
		try {			
			this.daoManager = DaoManagerBuilder.buildDaoManager(getInputStream(daoConfigFile));
		} catch (DaoException e) {
			e.printStackTrace();
		}

	}

	public IAccountDao getAccountDao() {
		if (accountDao==null) {
			accountDao = (IAccountDao) daoManager.getDao(IAccountDao.class,CONTEXT_NAME);
			return accountDao;
		}
		else 
			return accountDao;
	}
	

	public void startTrasaction() {
		System.out.println("FactoryIbatisDao start transaction");
		daoManager.startTransaction();
	}
	
	public void commitTransaction() {
		System.out.println("FactoryIbatisDao commit transaction");
		daoManager.commitTransaction();

	}
	
	public void roolbackTransaction() {
		System.out.println("FactoryIbatisDao rollback transaction");
		daoManager.endTransaction();
	}
	
	private InputStreamReader getInputStream(String file) {
		
		InputStreamReader isReader = null;
		InputStream inputStream = null;
		inputStream = this.getClass().getResourceAsStream(file);
				
		isReader = new InputStreamReader(inputStream);
		
		return isReader;
	}
	
	public String toString() {
		return "FactoryIbatisDao";
	}
	
}
